package com.lcredu.web;

/**
 * @author 黎长容
 * @date 2025-07-06 11:58
 */

import com.lcredu.entity.Admin;
import com.lcredu.service.AdminService;
import com.lcredu.service.impl.AdminServiceImpl;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.util.UUID;

@WebServlet(name = "AdminServlet", urlPatterns = "/AdminServlet")
public class AdminServlet extends BasicServlet {
    private AdminService adminService = new AdminServiceImpl();

    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        Admin admin = adminService.getAdmin(username, password);

        //每次请求前先获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("adminId".equals(cookie.getName())){
                    request.getSession().setAttribute("user", admin);
                    request.getRequestDispatcher("/views/manage/manage_menu.jsp").forward(request, response);
                }
            }
        }

        if (admin != null) {
            Cookie cookie = new Cookie("adminId", UUID.randomUUID().toString());
            cookie.setMaxAge(24 * 60 * 60);
            response.addCookie(cookie);
            request.getSession().setAttribute("user", admin);
            request.getRequestDispatcher("/views/manage/manage_menu.jsp").forward(request, response);

        } else {

            request.getRequestDispatcher("/views/manage/manage_login.jsp").forward(request, response);
        }
    }

    protected void sayHi(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Hi---hello");
    }
}